/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.emobile.biz.api.controller.ApiProfileController.java
 * <p>
 * 类产生时间: 2014/4/19 23:12
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.modules.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.common.constant.ConfigInfo;
import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.encrypt.DesAPPUtils;
import com.oceansoft.mobile.econsole.modules.api.util.ApiCodeToMessageUtil;
import com.oceansoft.mobile.econsole.modules.api.util.UserInfoUtil;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.member.entity.Member;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import com.oceansoft.mobile.econsole.modules.member.service.IWtMemberService;
import com.oceansoft.mobile.econsole.weixin.util.StrUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

import static com.oceansoft.mobile.econsole.common.constant.Constant.SMS_BIZ_REBIND_MOBILE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 客户端账号管理控制器
 *
 * @author: chenw
 * @time: 2014/4/19 23:12
 */
@RestController
@RequestMapping("api/profile")
public class
ApiProfileController extends BaseController {

    @Resource
    private IMemberService memberService;
    @Resource
    private IWtMemberService wtMemberService;
    @Resource
    protected ConfigInfo configInfo;

    /**
     * 用户密码重置
     */
    @RequestMapping(value = "pwd/reset", method = POST)
    public Result resetPassword(HttpServletRequest request) {
        String tel = request.getParameter("tel");
        String password = request.getParameter("password");
        String btnSendCode = request.getParameter("btnSendCode");

        if (!StringUtils.hasText(tel)) {
            return new Result(Result.FAILURE, "请输入手机号码");
        }
        if (!StringUtils.hasText(password)) {
            return new Result(Result.FAILURE, "请输入新密码");
        }
        if (!StringUtils.hasText(btnSendCode)) {
            return new Result(Result.FAILURE, "请输入验证码");
        }
        return super.resetPassword(tel, password, btnSendCode);
    }

    /**
     * 重新绑定手机号码
     *
     * @return Result
     */
    @RequestMapping(value = "mobile/rebind", method = POST)
    public Result rebindMobile(@RequestParam("id") String id,
                               @RequestParam("oldTel") String oldTel,
                               @RequestParam("newTel") String newTel,
                               @RequestParam("newCode") String newCode) {
        if (!StringUtils.hasText(id)) {
            return new Result(Result.FAILURE, "请输入身份证号");
        }
        if (!StringUtils.hasText(oldTel)) {
            return new Result(Result.FAILURE, "请输入原手机号码");
        }
        if (!StringUtils.hasText(newTel)) {
            return new Result(Result.FAILURE, "请输入新手机号码");
        }
        if (!StringUtils.hasText(newCode)) {
            return new Result(Result.FAILURE, "请输入新手机号验证码");
        }
        Result result = memberService.rebindUserMobile(SMS_BIZ_REBIND_MOBILE, id, oldTel, newTel, newCode);
        if (result.isSucc()) {
            WtMember member = getWxMemberSession();
            if (member != null) {
                member.setUserName(newTel);
                try {
                    member.setMobile(DesAPPUtils.encrypt(newTel));
                } catch (Exception e) {
                    e.printStackTrace();
                    return new Result(Result.FAILURE, "手机号加密出错");
                }
                saveWxMemberSession(member);
            }
        }
        return result;
    }

    /**
     * 客户端用户注册
     *
     * @param member AppUser
     * @return Result
     */
    @RequestMapping(value = "register", method = POST)
    public Result clientRegister(@RequestBody Member member) {
        return memberService.register(member);
    }

    /**
     * 供网厅使用 -- 保存用户接口
     *
     * @return Result
     */
/*    @RequestMapping(value = "synchappmember", method = POST)
    public Result synchAppMember(HttpServletRequest request) {
        String loginId = request.getParameter("loginId");
        if (StringUtils.isEmpty(loginId))
            return new Result(Result.FAILURE, "用户名不能为空!");
        String password = request.getParameter("password");
        if (StringUtils.isEmpty(loginId))
            return new Result(Result.FAILURE, "密码不能为空!");
        Member member = new Member();
        member.setLoginId(strHandle(loginId));
        member.setPassword(strHandle(password));
        member.setRealName(strHandle(request.getParameter("realName")));
        member.setEmail(strHandle(request.getParameter("email")));
        member.setAddress(strHandle(request.getParameter("address")));
        member.setMobile(strHandle(request.getParameter("mobile")));
        member.setTel(strHandle(request.getParameter("tel")));
        member.setIdCard(strHandle(request.getParameter("idCard")));
        member.setPassport(strHandle(request.getParameter("passport")));
        member.setUidTw(strHandle(request.getParameter("uidTw")));
        member.setGuid(strHandle(request.getParameter("guid")));
        member.setOrgId(strHandle(request.getParameter("orgId")));
        member.setCorporate(strHandle(request.getParameter("corporate")));
        member.setContacts(strHandle(request.getParameter("contacts")));
        member.setLpn(strHandle(request.getParameter("lpn")));
        member.setVin(strHandle(request.getParameter("vin")));
        member.setDrivingLic(strHandle(request.getParameter("drivingLic")));
        member.setFileId(strHandle(request.getParameter("fileId")));
        member.setUserSrc("P");
        return memberService.synChappMember(member);
    }*/

    /**
     * 供网厅使用 -- 更新用户接口
     *
     * @return Result
     */
/*    @RequestMapping(value = "updateappmember", method = POST)
    public Result synchUpateMember(HttpServletRequest request) {
        String guid = request.getParameter("guid");
        if (StringUtils.isEmpty(guid))
            return new Result(Result.FAILURE, "guid不能为空!");
        String password = request.getParameter("password");
        if (!StringUtils.isEmpty(password))
            password = MD5Util.getMD5String(password);
        Member mb = memberService.findByGuid(guid);
        if (null == mb)
            return new Result(Result.FAILURE, null, "该guid用户不存在");
        Member member = new Member();
        member.setPassword(strHandle(password));
        member.setRealName(strHandle(request.getParameter("realName")));
        member.setEmail(strHandle(request.getParameter("email")));
        member.setAddress(strHandle(request.getParameter("address")));
        member.setMobile(strHandle(request.getParameter("mobile")));
        member.setTel(strHandle(request.getParameter("tel")));
        member.setIdCard(strHandle(request.getParameter("idCard")));
        member.setPassport(strHandle(request.getParameter("passport")));
        member.setUidTw(strHandle(request.getParameter("uidTw")));
        member.setOrgId(strHandle(request.getParameter("orgId")));
        member.setCorporate(strHandle(request.getParameter("corporate")));
        member.setContacts(strHandle(request.getParameter("contacts")));
        member.setLpn(strHandle(request.getParameter("lpn")));
        member.setVin(strHandle(request.getParameter("vin")));
        member.setDrivingLic(strHandle(request.getParameter("drivingLic")));
        member.setFileId(strHandle(request.getParameter("fileId")));
        member.setGuid(strHandle(guid));
        return memberService.update(member);
    }*/
    private String strHandle(String str) {
        if (StringUtils.isEmpty(str))
            return "";
        return str;
    }

    /**
     * 更新用户信息 - 并更新网厅用户
     *
     * @return Result
     */
    @RequestMapping(value = "updatemember", method = POST)
    public Result updateMember(@RequestBody Member user) {
        return super.updateMember(user);
    }

    /**
     * 登录认证
     *
     * @param user 登录用户
     * @return Result
     */
    @RequestMapping(value = "auth", method = POST)
    public Result loginAuthentication(@RequestBody Member user) throws IOException {
        try {

            return memberService.userLoginAuthentication(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "用户登录失败");
        }
    }


    /**
     * 传入openId、验证是否已经绑定
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "wx_auth", method = POST)
    public Result openIdAuth(@RequestBody Member member) {
        if (org.apache.commons.lang.StringUtils.isBlank(member.getOpenId())) {
            return new Result(Result.FAILURE, "请上传openId");
        }

        WtMember wtMember = wtMemberService.getWtMemberByOpenid(member.getOpenId());
        if (wtMember != null) {
            saveWxMemberSession(wtMember);
            return new Result(Result.SUCC, member, "认证成功");
        } else {
            return new Result(Result.FAILURE, member, "认证失败");
        }
    }

    /**
     * 传入openId认证失败，进入登录页面
     * 传入openId、loginId、password
     *
     * @param member 登录用户
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "wx_login", method = POST)
    public Result openIdLogin(@RequestBody Member member) throws IOException {
        JSONObject jsonObject = new JSONObject();
        String loginId = member.getLoginId();
        String password = member.getPassword();
        String openId = member.getOpenId();
        String userSrc = member.getUserSrc();

        if (StrUtil.hasBlank(loginId, password)) {
            return new Result(Result.FAILURE, "用户名/密码为空");
        }
        if (Objects.equals(Constant.WECHAT_USER, userSrc)) {
            openId = Strings.isNullOrEmpty(openId) ? getSessionOpenId() : openId;
            jsonObject.put("wxOpenId", openId);
            if (Strings.isNullOrEmpty(openId)) {
                return new Result(Result.FAILURE, "openId为空");
            }
        }
        jsonObject.put("acountId", loginId);
        jsonObject.put("password", password);
        try {
            String url = configInfo.getServiceInterfaceAddress() + "/member/login";
            System.out.println(jsonObject);
            String res = HttpClientUtil.post(url, jsonObject);
            JSONObject resultJson = JSONObject.parseObject(res);

            boolean flag = resultJson.getBooleanValue("succ");
            // 用户信息
            WtMember wtMember = null;
            if (flag) {
                wtMember = UserInfoUtil.getWtMember(resultJson.getString("data"));
                saveWxMemberSession(wtMember);
            }
            Result result = new Result(flag, resultJson.getIntValue("code"), wtMember,
                    StringUtils.isEmpty(resultJson.getString("msg")) ? ApiCodeToMessageUtil.codeToMessage(resultJson.getString("code")) : resultJson.getString("msg"));

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "用户登录失败");
        }
    }

    /**
     * 传入openId认证失败，进入登录页面
     * 客户端用户注册
     *
     * @param member AppUser
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "wx_register", method = POST)
    public Result openIdRegister(@RequestBody Member member) {

        String password = member.getPassword();
        String mobile = member.getMobile();
        String validateCode = member.getValidateCode();
        String openId = member.getOpenId();
        String userSrc = member.getUserSrc();
        if (StrUtil.hasBlank(password, mobile, validateCode)) {
            return new Result(Result.FAILURE, "密码/手机号/验证码不能为空");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("acountId", mobile);// 手机号
        jsonObject.put("password", password);// 密码
        jsonObject.put("source", userSrc);// 用户来源
        jsonObject.put("smscode", validateCode);// 验证码

        // 微信端注册用户必须有openId
        if (Objects.equals(Constant.WECHAT_USER, userSrc)) {
            openId = Strings.isNullOrEmpty(openId) ? getSessionOpenId() : openId;
            if (Strings.isNullOrEmpty(openId)) {
                return new Result(Result.FAILURE, "openId为空");
            }
            jsonObject.put("wxOpenId", openId);// openid
        }

        System.out.println(jsonObject.toJSONString());//{"acountId":"13646213873","password":"123456","wxOpenId":"123456","smscode":"1234","source":"WEI"}
        try {
            // 注册接口
            String res = HttpClientUtil.post(configInfo.getServiceInterfaceAddress() + "/member/", jsonObject);
            System.out.println(res);
            JSONObject resultJson = JSONObject.parseObject(res);
            Result result = new Result(Boolean.parseBoolean(resultJson.getString("succ")),
                    Integer.parseInt(resultJson.getString("code")), resultJson.get("data"),
                    StringUtils.isEmpty(resultJson.getString("msg")) ? ApiCodeToMessageUtil.codeToMessage(resultJson.getString("code")) : resultJson.getString("msg"));
            if (result.isSucc()) {
                // 获取用户信息放入session
                String memberString = HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress() + "/member/account/" + mobile);
                JSONObject memberJson = JSONObject.parseObject(memberString);
                if (memberJson.getBooleanValue("succ")) {
                    saveWxMemberSession(UserInfoUtil.getWtMember(memberJson.getString("data")));
                }
            }
            return result;
        } catch (Exception e) {
            return new Result(Result.FAILURE, "访问接口异常");
        }

    }

}
